﻿using TbShop.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TbShop.Business.Components
{
    public class AuthorityBC : ServiceComponents<Authority>, IBusinessContractBase<Authority>
    {
        /// <summary>
        /// 通过角色获取权限
        /// </summary>
        /// <param name="authId"></param>
        /// <returns></returns>
        public IEnumerable<int> GetAuthoritysForRole(int authId)
        {
            return this.GetAll().Where(x => x.Id == authId || x.ParentId == authId).Select(x => x.Id);
        }
        /// <summary>
        /// 根据用户ID和权限Code判断该用户是否有该权限
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="authorityIdentity">权限Code</param>
        /// <returns></returns>
        public bool IsUserAuthority(string userId, string authorityIdentity)
        {
            var result = from ur in this.CurrentDBContext.AspNetUserRoles
                         join ra in CurrentDBContext.RoleAuthoritys on ur.RoleId equals ra.RoleId
                         join a in CurrentDBContext.Authoritys on ra.AuthorityId equals a.Id
                         where ur.UserId == userId && a.Code == authorityIdentity && !ra.IsDeleted && !a.IsDeleted
                         select 1;
            return result.Count() == 1;
        }
        /// <summary>
        /// 获取权限
        /// </summary>
        /// <returns></returns>
        public List<Authority> GetAuthoryModelList()
        {
            var result = this.GetAll();
            return GetChildAuthoritys(this.GetAll().ToList(), 0);
        }

        public List<Authority> GetChildAuthoritys(List<Authority> datas, int id)
        {
            var resultData = new List<Authority>();
            foreach (var item in datas.Where(p => p.ParentId == id))
            {
                item.ChildAuthoritys = GetChildAuthoritys(datas, item.Id).ToList();
                resultData.Add(item);
            }
            return resultData;
        }
        /// <summary>
        /// 根据id获取父级
        /// </summary>
        /// <param name="authId"></param>
        /// <returns></returns>
        public int[] GetParentById(int authId)
        {
            int[] ids = new int[3] { 0, 0, 0 };
            ids[0] = authId;
            var data = this.Get(authId);
            var parents = this.GetAll().Where(a => a.Id == data.ParentId).ToList();
            if (parents.Any())
            {
                var parent = parents.FirstOrDefault();
                ids[1] = parent.Id;
                var fist = this.GetAll().Where(a => a.Id == parent.ParentId).ToList();
                if (fist.Any())
                {
                    ids[2] = fist.FirstOrDefault().Id;
                }
            }
            return ids;
        }
    }
}
